package org.common.utils;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

public class RequestUtils {

    /**
     * 获取请求端口
     *
     * @param request 请求
     */
    public static String getHost(final HttpServletRequest request) {
        final String dlUrl = request.getHeader("X-Forwarded-Host");
        return CommonUtils.isEmpty(dlUrl) ? dlUrl : request.getHeader("host").split(":")[0];
    }

    /**
     * 获取请求IP
     *
     * @param request 请求
     */
    public static String getServerIp(final HttpServletRequest request) {
        return request.getLocalAddr();
    }

    /**
     * 获取页面请求路径
     *
     * @param request 请求
     * @param string  数据请求前缀
     */
    private static String getPageUrl(final HttpServletRequest request, final String string) {
        final String sServiceName = request.getServerName();
        StringBuilder builder = new StringBuilder();
        builder.append(string).append("://").append(sServiceName);
        if (80 != request.getServerPort() && 443 != request.getServerPort()) {
            builder.append(":").append(request.getServerPort());
        }
        builder.append(request.getContextPath());
        return builder.toString();
    }

    /**
     * 获取页面请求路径
     *
     * @param request 请求
     */
    public static String getPageUrl(final HttpServletRequest request) {
        return getPageUrl(request, "http");
    }

    /**
     * 获取带参URL
     * @param request 请求
     */
    public static String getCompleteURL(final HttpServletRequest request) {
        final StringBuffer uri = request.getRequestURL();
        final Map<String, String[]> map = request.getParameterMap();
        final Set<Map.Entry<String, String[]>> entry = map.entrySet();
        final Iterator<Map.Entry<String, String[]>> iterator = entry.iterator();
        final StringBuilder sb = new StringBuilder();
        while (iterator.hasNext()) {
            final Map.Entry<String, String[]> item = iterator.next();
            final String key = item.getKey();
            for (final String value : item.getValue()) {
                sb.append(key).append("=").append(value).append("&");
            }
        }
        final String string = sb.toString();
        uri.append("?").append(string.substring(0, string.lastIndexOf("&")));
        return uri.toString();
    }

    /**
     * 获取当前请求的URL
     * @param request 请求
     */
    public static String getURL(final HttpServletRequest request) {
        return request.getRequestURL().toString();
    }

    /**
     * 获取上一个请求的URL
     * @param request 请求
     */
    public static String getPreviousURL(final HttpServletRequest request) {
        return request.getHeader("Referer");
    }
}
